<!--
 * @Author: wangjian
 * 656876071@qq.com
 * @Date: 2024-08-12 16:05:21
 * @LastEditTime: 2024-09-19 10:46:59
 * @FilePath: src/views/sys/role/RoleForm.vue
 * @Description: 
 -->
<script setup lang="ts">
import {useForm} from './Hooks'
import {SIMPLE_FORM_SUBMIT_KEY} from "@/core/common/hooks/FormHooks";
import {ref, watch} from "vue";
import {useMenu} from "@/views/sys/api/SysMenuApi";
import type {Ret} from "@/core/utils/request";

const callback = defineEmits([SIMPLE_FORM_SUBMIT_KEY])
const {
  form,
  modalIsVisible,
  modalIsSubmitting,
  modalSubmit,
  showEditForm,
  showAddForm,
  menuTree
} = useForm(callback)

const overrideShowAddForm = () => {
  // 初始化选中框
  checkedKeys.value = []
  // 原始逻辑
  showAddForm()
}
const overrideShowEditForm = (id:string) => {
  // 初始化选中框
  checkedKeys.value = []
  // 原始逻辑
  showEditForm(id)
}
defineExpose({
  showAddForm: overrideShowAddForm,
  showEditForm: overrideShowEditForm
})


const checkedKeys = ref<[]>([])

function treeChecked(selectedKeys: [], e: any) {
  let finalKeys = [...selectedKeys]
  form.value.menuIds = finalKeys.concat(e.halfCheckedKeys)
  console.log(form.value.menuIds)
}

const {getMenuTree} = useMenu()
// 初始化菜单树
watch(modalIsVisible, (newVal) => {
  if (!newVal) {
    return
  }
  getMenuTree().then((res: any | Ret) => {
    menuTree.value = res.data
  })
})

// 菜单树变化为实际选中
watch(form, (newVal) => {
  if (newVal.menuIds) {
    checkedKeys.value = newVal.menuIds
  }
})

</script>

<template>
  <a-modal v-model:open="modalIsVisible" title="角色目录维护" width="30rem" :maskClosable="false">
    <template #footer>
      <a-button key="back" @click="modalIsVisible = false">取消</a-button>
      <a-button :loading="modalIsSubmitting" key="submit" type="primary" @click="modalSubmit">录入</a-button>
    </template>
    <a-form :disabled="modalIsSubmitting" :label-col="{span:5}" :wrapper-col="{span: 18}" label-align="right">
      <a-form-item label="角色名称">
        <a-input v-model:value="form.roleName" placeholder="请输入角色名称"/>
      </a-form-item>
      <a-form-item label="角色编码">
        <a-input v-model:value="form.roleCode" placeholder="请输入角色编码"/>
      </a-form-item>
      <a-form-item label="排序">
        <a-input v-model:value="form.sortNum" placeholder="请输入排序"/>
      </a-form-item>
      <a-form-item label="数据权限">
        <a-input v-model:value="form.dataScope" placeholder="请输入数据权限"/>
      </a-form-item>
      <a-form-item label="备注">
        <a-input v-model:value="form.remark" placeholder="请输入备注"/>
      </a-form-item>
      <a-tree
          v-model:checkedKeys="checkedKeys"
          checkable
          show-line
          :tree-data="menuTree"
          :fieldNames="{
            title:'menuName',
            key:'menuId'
          }"
          @check="treeChecked"
      >
      </a-tree>
    </a-form>
  </a-modal>
</template>

<style scoped>

</style>